import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { changeAllAction, delAction, editAction } from '../store/action/todo';

export default function Main() {
  const state = useSelector((state) => state);
  // console.log('state -----> ', state);

  // 4. useSelector获取store中的数据
  const { list } = useSelector((state) => state.todo);
  const { name } = useSelector((state) => state.user);
  // console.log('name -----> ', name);
  // console.log('list -----> ', list);
  const isAll = list.length > 0 && list.every((item) => item.done);
  // console.log('isAll -----> ', isAll);
  const dispatch = useDispatch();
  return (
    <section className="main">
      <input
        checked={isAll}
        // 这里注意，拿的应该是 e.target.checked，不是e.target.value
        onChange={(e) => dispatch(changeAllAction(e.target.checked))}
        id="toggle-all"
        className="toggle-all"
        type="checkbox"
      />
      <label htmlFor="toggle-all">全选</label>
      <ul className="todo-list">
        {list.map((item) => {
          return (
            <li className={item.done ? 'completed' : ''} key={item.id}>
              <div className="view">
                <input
                  // 记得是调用 editAction()
                  onChange={() => {
                    dispatch(editAction(item.id));
                  }}
                  className="toggle"
                  type="checkbox"
                  checked={item.done}
                />
                <label>{item.name}</label>
                <button
                  className="destroy"
                  onClick={() => dispatch(delAction(item.id))}
                ></button>
              </div>
            </li>
          );
        })}
      </ul>
    </section>
  );
}
